package com.lamer.console.common.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lamer.console.common.api.ApiResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        ApiResult<Object> failed = ApiResult.failed();
        if(e instanceof BadCredentialsException){
            failed.setMessage("登陆失败，密码错误");
        } else if(e instanceof DisabledException){
            failed.setMessage("登陆失败，账号被禁用");
        } else {
            failed.setMessage("登录失败，未知错误");
        }
        httpServletResponse.setContentType("text/json;charset=UTF8");
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(failed));
    }
}
